<template>
  <div>
    <el-dialog :title="roleForm.id?'编辑角色':'新增角色'" :visible="showDialog" @close="btnCancel">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { addRole, getRoleDetail, updateRole } from '@/api/setting'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }

  },

  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    //   获取角色详情函数
    async getRoleDetail(id) {
      this.roleForm = await getRoleDetail(id)
    },

    // 点击确定按钮触发函数
    async btnOK() {
    //   console.log(1)
      // 校验表单
      await this.$refs.roleForm.validate()
      if (this.roleForm.id) {
        //   调用编辑接口
        await updateRole(this.roleForm)
        //   提示用户
        this.$message.success('编辑成功')
      } else {
        await addRole(this.roleForm)
        //   提示用户
        this.$message.success('新增成功')
      }

      //   告诉父组件关闭弹窗
      this.$emit('update:showDialog', false)
      // 通知父组件更新数据
      this.$emit('editRole')
      // 清空表单内容
      this.$refs.roleForm.resetFields()
    },

    // 点击取消按钮触发的函数
    btnCancel() {
      // 清空实质内容
      this.roleForm = {
        name: '',
        description: ''
      }
      // 清空表单内容
      this.$refs.roleForm.resetFields()
      // 关闭弹窗
      this.$emit('update:showDialog', false)
    }
  }

}
</script>

<style>

</style>
